<?php
/**
 * 主类文件
 * 
 * @author ShuangYa
 * @package TiebaMonitor
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2016 ShuangYa
 * @license http://lab.sylingd.com/go/TiebaMonitor/license
 */


set_exception_handler(function($e) {
	if ($e instanceof TiebaException) {
		TiebaMonitor::showLog('Error: ' . $e->getMessage());
	}
});
class TiebaMonitor {
	private $config;
	private $word;
	private $thread;
	private $whiteList;
	private $checkInterval;
	private $debug;
	public function __construct($config) {
		$config['fid'] = TiebaForum::getFid($config['kw']);
		$this->word = '/(' . $config['word'] . ')/i';
		//间隔
		if (isset($config['interval'])) {
			$this->checkInterval = $config['interval'];
		} elseif (defined('INTERVAL')) {
			$this->checkInterval = INTERVAL;
		} else {
			$this->checkInterval = 30;
		}
		//调试
		if (isset($config['debug'])) {
			$this->debug = $config['debug'];
		} elseif (defined('DEBUG')) {
			$this->debug = DEBUG;
		} else {
			$this->debug = FALSE;
		}
		//白名单
		$this->whiteList = explode(',', $config['whiteList']);
		$this->config = $config;
		//建立索引
		static::showLog('开始运行');
		$this->thread = [];
		$list = TiebaForum::getThreadList($this->config['kw']);
		foreach ($list as $thread) {
			$this->thread[$thread['id']] = $thread['last_time_int'];
		}
	}
	//判断贴子是否违规并进行相关操作
	public function checkPost($post, $threadId) {
		foreach ($post['content'] as $content) {
			if ($content['type'] != 0) {
				//判断是否为文字
				continue;
			}
			//去掉空格
			$content['text'] = str_replace(' ', '', $content['text']);
			//判断是否有违禁词
			if (preg_match($this->word, $content['text'], $matches)) {
				//判断是否为白名单
				if (in_array($post['author']['name'], $this->whiteList, TRUE)) {
					static::showLog('用户 ' . $post['author']['name'] . ' 发布了违规贴，但处于白名单');
					continue;
				}
				//获取违禁词
				// $banWord = $matches[0];
				//是否应该封禁
				if ($this->config['ban'] > 0 && ($post['author']['level_id'] <= $this->config['level'] || $post['author']['is_like'] == 0)) {
					static::showLog('封禁用户：' . $post['author']['name']);
					TiebaManage::ban($this->config['BDUSS'], $this->config['ban'], $this->config['reason'], $post['author']['name'], $threadId, $this->config['kw']);
				}
				//自动删帖
				if ($post['floor'] == 1) {
					static::showLog('删除主题：http://tieba.baidu.com/p/' . $threadId);
					TiebaManage::delThread($this->config['BDUSS'], $this->config['fid'], $threadId);
				} else {
					static::showLog('删除回贴：http://tieba.baidu.com/p/' . $threadId . '。贴子ID：' . $post['id']);
					TiebaManage::delPost($this->config['BDUSS'], $this->config['fid'], $threadId, $post['id'], FALSE);
				}
			}
		}
	}
	//日志记录
	public static function showLog($message) {
		if (stripos(PHP_OS, 'win') !== FALSE) {
			echo iconv('UTF-8', 'GBK', $message);
		} else {
			echo $message;
		}
		echo "\n";
	}
	//调试日志
	public static function debugLog($message) {
		if (!$this->debug) {
			return;
		}
		static::showLog('DEBUG: ' . $message);
	}
	//开始监控
	public function check() {
		$list = TiebaForum::getThreadList($this->config['kw']);
		foreach ($list as $thread) {
			if (!isset($this->thread[$thread['id']]) && ($thread['create_time'] - time()) <= ($this->checkInterval * 2)) {
				//新的主题
				//跳过精品贴
				if ($thread['is_good'] == 1) {
					continue;
				}
				//检查标题
				if (preg_match($this->word, $thread['title'], $matches)) {
					//判断是否为白名单
					if (in_array($thread['author']['name'], $this->whiteList, TRUE)) {
						static::showLog('用户 ' . $thread['author']['name'] . ' 发布了违规贴，但处于白名单');
					} else {
						//主题帖无法判断等级
						if ($this->config['ban'] > 0) {
							static::showLog('封禁用户：' . $thread['author']['name']);
							TiebaManage::ban($this->config['BDUSS'], $this->config['ban'], $this->config['reason'], $thread['author']['name'], $thread['id'], $this->config['kw']);
						}
						static::showLog('删除主题：http://tieba.baidu.com/p/' . $thread['id']);
						TiebaManage::delThread($this->config['BDUSS'], $this->config['fid'], $thread['id']);
					}
				}
				//抓取内容
				$threadDetail = TiebaForum::getThread($thread['id']);
				if (isset($threadDetail['post_list'])) {
					foreach ($threadDetail['post_list'] as $k => $post) {
						$this->checkPost($post, $thread['id']);
						//超过10楼则跳出
						if ($k >= 10) {
							break;
						}
					}
				}
			} else {
				//视为已有主题，判断最后发贴
				if (!isset($this->thread[$thread['id']])) {
					//老贴子被顶上来了
					$threadDetail = TiebaForum::getThread($thread['id'], 1, TRUE);
					if (isset($threadDetail['post_list'])) {
						foreach ($threadDetail['post_list'] as $newPost) {
							if ($newPost['time'] - time() > ($this->checkInterval * 2)) {
								break;
							}
							$this->checkPost($newPost, $thread['id']);
						}
					}
					$this->thread[$thread['id']] = $thread['last_time_int'];
				} elseif ($this->thread[$thread['id']] !== $thread['last_time_int']) {
					//获取最新贴子，只取至last_time_int
					$threadDetail = TiebaForum::getThread($thread['id'], 1, TRUE);
					if (isset($threadDetail['post_list'])) {
						foreach ($threadDetail['post_list'] as $newPost) {
							if ($newPost['time'] <= $this->thread[$thread['id']]) {
								break;
							}
							$this->checkPost($newPost, $thread['id']);
						}
					}
					$this->thread[$thread['id']] = $thread['last_time_int'];
				} else {
					continue;
				}
			}
		}
	}
}